"""
MEMESA-TOOLS
============
Model preparation, vertex enumeration and vertex analysis tools developed as
part of the MEMESA project.

    Copyright (C) 2009-2012 Brett G. Olivier and Steven M. Kelk

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

Author: Brett G. Olivier
Contact email: bgoli@users.sourceforge.net

"""

import os, time, numpy
cDir = os.path.dirname(os.path.abspath(os.sys.argv[0]))

# Set userdata here #

# core model
##  work_dir = 'core_memesa_model'
##  model_name_list = ['core_memesa_model']
##  infinity_bound = 1000

# Ecoli
##  work_dir = 'iJR904M'
##  model_name_list = ['Ecoli_iJR904.thr']
##  infinity_bound = 999999

# Big Ecoli
#work_dir = 'iAF1260'
#model_name_list = ['Ecoli_iAF1260.glc']
#infinity_bound = 999999

## Vin
#work_dir = 'vin'
#model_name_list = ['vin']
#infinity_bound = 10000

# Timo
work_dir = 'Test'
#model_name_list = ['toy_model_s1.l2', 'toy_model_s2.l2']
#infinity_bound = 1000.0
model_name_list = ['Ecoli_iAF1260_noox.glc_10.l2','Ecoli_iAF1260_noox.glc_10_split.l2','Ecoli_iAF1260_ox.glc_8_split.l2']
model_name_list = ['Ecoli_iAF1260_ox.glc_8_split.l2']
infinity_bound = 999999.0


# End userdata #

### Active script ###

from pyscescbm.CBVersion import __DEBUG__, __version__
from pyscescbm import CBRead, CBWrite, CBTools
from pyscescbm import CBSolver as slv

for model_name in model_name_list:
    if model_name.endswith('.xml'):
        model_name = model_name[:-4]
    model_file = model_name + '.xml'
    model_dir = os.path.join(cDir, work_dir, 'sbml')
    work_dir2 = os.path.join(cDir, work_dir, 'steven')

    work_dir2 = os.path.join(cDir, work_dir2)
    if not os.path.exists(work_dir2):
        os.makedirs(work_dir2)

    mod = CBRead.readSBML2FBA(model_file, work_dir=model_dir)
    if mod.objectives == []:
        print 'Trying level 3'
        mod = CBRead.readSBML3FBC(model_file, work_dir=model_dir)
        time.sleep(10)

    mod.id = model_name

    # test models

    CBTools.processBiGGchemFormula(mod)
    #CBTools.processSBMLAnnotationNotes(mod, annotation_key='note')

    print '\nAttempting to delete bounds for biomass reaction,', mod.getActiveObjective().getFluxObjectiveReactions()[0]
    mod.deleteBoundsForReactionId(mod.getActiveObjective().getFluxObjectiveReactions()[0])

    mLP = slv.analyzeModel(mod, return_lp_obj=True)
    CBWrite.printFBASolution(mod)
    tmp_mid = mod.id+'_cplex'
    ##  mod.id = mod.id+'_withinf'
    ##  CBWrite.exportModel(mod, fmt='hformat', work_dir=work_dir2)

    CBTools.countedPause(5)

    mod.id = tmp_mid

    print '\n%s\n' % len(mod.flux_bounds)
    mod.changeAllFluxBoundsWithValue(infinity_bound, 'Infinity')
    mod.changeAllFluxBoundsWithValue(-infinity_bound, '-Infinity')
    mod.changeAllFluxBoundsWithValue(numpy.inf, 'Infinity')
    mod.changeAllFluxBoundsWithValue(-numpy.inf, '-Infinity')

    print '\n%s\n' % len(mod.flux_bounds)
    slv.analyzeModel(mod, lpFname=os.path.join(work_dir2, mod.id), oldlpgen=False)
    CBWrite.exportModel(mod, fmt='lp', work_dir=work_dir2)

    mod.id = mod.id.replace('_cplex','')+'.noinf'
    print '\n%s\n' % len(mod.flux_bounds)
    mod.deleteAllFluxBoundsWithValue('Infinity')
    mod.deleteAllFluxBoundsWithValue('-Infinity')
    print '\n%s\n' % len(mod.flux_bounds)
    CBWrite.exportModel(mod, fmt='all', work_dir=work_dir2, use_rational=True)
    del mod
